#!/usr/bin/env python
#
# Licensed under the BSD license.  See full license in LICENSE file.
# http://www.lightshowpi.com/
#
# Author: Todd Giles (todd@lightshowpi.com)
# Author: Chris Usey (chris.usey@gmail.com)
# Author: Ryan Jennings
# Author: Paul Dunn (dunnsept@gmail.com)
"""Play any audio file and synchronize lights to the music

Modified from original synchronized_lights.py
see original file for details

Sample usage:

sudo python play.py

Third party dependencies:

Lightshowpi must be installed, configured and working before this one will work
"""
#todo clean these up, not all are needed in this one pd
import argparse
import csv
import fcntl
import gzip
import logging
import os
import random
import sys
import time
import socket

import configuration_manager as cm

import hardware_controller as hc

#need to move to config mgr
port = 8888

# Configurations - TODO(todd): Move more of this into configuration manager
_CONFIG = cm.CONFIG


#CHUNK_SIZE = 2048  # Use a multiple of 8



# TODO(todd): Refactor this to make it more readable / modular.
def main():
    '''main'''
   

try:
    # Initialize Lights
    hc.initialize()
   
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind(("",port))

    while 1:
       

        data, addr = s.recvfrom(1024)
        i2,b2 = data.split("=")
        i = int(i2)
        brightness = float(b2)
       # print str(i2) + "=" + str(b2)
        if not hc.is_pin_pwm(i):
                # If pin is on / off mode we'll turn on at 1/2 brightness
            if (brightness > 0.44):
                hc.turn_on_light(i, True)
            else:
                hc.turn_off_light(i, True)
        else:
                hc.turn_on_light(i, True, int(brightness*60))

    
except KeyboardInterrupt:
        pass
finally:
        print "\nStopping"
        s.close()
        hc.clean_up()
    # We're done, turn it all off and clean up things ;)
    

if __name__ == "__main__":
    main()
